//package com.ai.chat.module.user.service.impl;
//
//import com.ai.chat.module.business.websocket.WebSocketController;
//import com.ai.chat.module.business.domain.vo.UserMessage;
//import com.ai.chat.module.user.mapper.ChatContentMapper;
//import com.ai.chat.module.user.mapper.UserImageMapper;
//import com.ai.chat.module.user.service.ChatService;
//import com.alibaba.fastjson2.JSONObject;
//import com.ai.chat.module.user.domain.req.UserTalkReq;
//import com.ai.chat.common.base.ThreadLocalContext;
//import com.ai.chat.common.constant.StringConstant;
//import com.ai.chat.module.user.domain.entity.ChatContentEntity;
//import com.ai.chat.module.user.domain.entity.UserImageEntity;
//import com.ai.chat.config.properties.UserInfoProperty;
//import com.ai.chat.module.user.domain.vo.UserLoginInfo;
//import com.ai.chat.module.user.domain.vo.UserTimeVo;
//import com.ai.chat.util.DateUtils;
//import com.ai.chat.util.FileUtils;
//import com.ai.chat.util.MrHeOpenAiService;
//import com.theokanning.openai.image.CreateImageRequest;
//import com.theokanning.openai.image.Image;
//import io.github.asleepyfish.enums.audio.AudioResponseFormatEnum;
//import io.github.asleepyfish.enums.exception.ChatGPTErrorEnum;
//import io.github.asleepyfish.exception.ChatGPTException;
//import io.github.asleepyfish.service.OpenAiProxyService;
//import io.github.asleepyfish.util.OpenAiUtils;
//import lombok.SneakyThrows;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.core.io.Resource;
//import org.springframework.scheduling.annotation.Async;
//import org.springframework.stereotype.Service;
//import org.springframework.web.context.request.RequestContextHolder;
//import org.springframework.web.context.request.ServletRequestAttributes;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.imageio.ImageIO;
//import javax.servlet.AsyncContext;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import javax.websocket.Session;
//import java.awt.image.BufferedImage;
//import java.io.File;
//import java.io.IOException;
//import java.io.OutputStream;
//import java.util.List;
//import java.util.stream.Collectors;
//import java.util.zip.ZipEntry;
//import java.util.zip.ZipOutputStream;
//
//
///**
//
// * @author: MrHeg
// * @create: 2023-09-01 20:37
// * @description:
// **/
//@Slf4j
////@Service(value = "chat3Service")
//public class Chat3ServiceImpl implements ChatService {
////    @Autowired
//    UserImageMapper userImageMapper;
//
//    //        @Autowired
//    OpenAiProxyService openAiProxyService;
//
//    //      @Autowired
//    private MrHeOpenAiService mrHeOpenAiUtil;
//
//    //    @Autowired
//    private ChatContentMapper chatContentMapper;
//
//    //    @Autowired
//    private UserInfoProperty userInfo;
//
//    @Override
//    public List<String> talk(String message) {
//      return null;
//    }
//
//    private void insertUserChat(UserTimeVo userTimeVo) {
//        long costTime = userTimeVo.getLastTime() - userTimeVo.getBeginTime();
//        String chatGptTalk = userTimeVo.getChatGptTalk();
//        String askContent = userTimeVo.getAskContent();
//        String robotId = userTimeVo.getRobotId();
//        UserLoginInfo userInfo = ThreadLocalContext.getUserLoginInfo();
//        ChatContentEntity chatContent = new ChatContentEntity();
//        chatContent.setUserId(userInfo.getUuid());
//        chatContent.setChatGpt(chatGptTalk );
//        chatContent.setContent(askContent);
//        chatContent.setRobotId(robotId);
//        chatContent.setCostTime(Math.toIntExact( costTime));
//        int insert = chatContentMapper.insert(chatContent);
//        log.info("进行数据入库 {},insert:{}", JSONObject.toJSONString(chatContent),insert);
//    }
//
//    @Override
//    public void talkVue(UserTalkReq userTalkReq, HttpServletResponse response) throws IOException {
//        String message = userTalkReq.getMessage();
//        String sessionId = userTalkReq.getRobotId();
//        long start = System.currentTimeMillis();
//        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = sra.getRequest();
//        final AsyncContext asyncContext = request.startAsync();
//        asyncContext.setTimeout(20000); // 设置超时时间(毫秒)
//        response.setContentType("text/event-stream");
//        response.setCharacterEncoding("UTF-8");
//        // 禁用缓存
//        response.setHeader("Cache-Control", "no-cache");
//        UserTimeVo userTimeVo = new UserTimeVo();
//        userTimeVo.setAskContent(message);
//        userTimeVo.setStartTime(System.currentTimeMillis());
//        userTimeVo.setUser(sessionId);
//        userTimeVo.setRobotId(sessionId);
//        //mrHeOpenAiUtil.createStreamChatCompletion(userTimeVo, response.getOutputStream());
//        insertUserChat(userTimeVo);
//
//    }
//
//
//
//    @Override
//    public List<String> createImage(String desc) {
//        List<String> imageList = OpenAiUtils.createImage(desc);
//
//        return imageList;
//    }
//
//
//
//    @Override
//    public void downloadImage(String desc, HttpServletResponse response) throws Exception{
//        // OpenAiUtils.downloadImage(desc, response);
//        UserLoginInfo userLoginInfo = ThreadLocalContext.getUserLoginInfo();
//        String userUUidId = userLoginInfo.getUuid();
//        int userId = userLoginInfo.getId();
//        CreateImageRequest request = MrHeOpenAiService.createImageRequest(desc);
//        String realPath =
//                String.format("%s/%s/%s%s", userInfo.getBaseUrl(),
//                        userId , DateUtils.getTransDateTime() ,".png");
//        log.info("文件创建目录为[{}]",realPath);
//        File file = FileUtils.createSaveFile(realPath);
//        List<String> imageBase64 = openAiProxyService.createImages(request).getData().stream()
//                .map(Image::getB64Json).collect(Collectors.toList());
//        BufferedImage base64Image = MrHeOpenAiService.getImageFromBase64(imageBase64.get(0));
//        asyncSaveImage(userUUidId, realPath, file, base64Image);
//        dealDowanload(response,   imageBase64);
//    }
//
//    @Async("dealImageTask")
//    public void asyncSaveImage(String userUUidId, String realPath, File file, BufferedImage base64Image) throws IOException {
//        boolean png = ImageIO.write(base64Image, "png", file);
//        if (png) {
//            Long sendMessageTime = (Long) ThreadLocalContext.get(StringConstant.CURRENT_TIME);
//            long currentTime = System.currentTimeMillis();
//            UserImageEntity userImage = new UserImageEntity();
//            userImage.setFilePath(realPath);
//            userImage.setUserId(userUUidId);
//            userImageMapper.insert(userImage);
//        }
//        log.info("图片的真实链接为: "+ realPath);
//    }
//
//
//    private void dealDowanload(HttpServletResponse response, List<String> imageBase64) {
//        try (OutputStream os = response.getOutputStream()) {
//            if (imageBase64.size() == 1) {
//                response.setContentType("image/png");
//                response.setHeader("Content-Disposition", "attachment; filename=generated.png");
//                BufferedImage bufferedImage =  MrHeOpenAiService.getImageFromBase64(imageBase64.get(0));
//                ImageIO.write(bufferedImage, "png", os);
//            } else {
//                response.setContentType("application/zip");
//                response.setHeader("Content-Disposition", "attachment; filename=images.zip");
//                try (ZipOutputStream zipOut = new ZipOutputStream(os)) {
//                    for (int i = 0; i < imageBase64.size(); i++) {
//                        BufferedImage bufferedImage = MrHeOpenAiService.getImageFromBase64(imageBase64.get(i));
//                        ZipEntry zipEntry = new ZipEntry("image" + (i + 1) + ".png");
//                        zipOut.putNextEntry(zipEntry);
//                        ImageIO.write(bufferedImage, "png", zipOut);
//                        zipOut.closeEntry();
//                    }
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new ChatGPTException(ChatGPTErrorEnum.DOWNLOAD_IMAGE_ERROR);
//        }
//    }
//
//    @Override
//    public String transferVoice(MultipartFile file) {
//        return null;
//    }
//
//    @Override
//    @SneakyThrows
//    public String voice2Text(MultipartFile file) {
//        Resource resource = file.getResource();
//        File originFile = resource.getFile();
//        String fileText = OpenAiUtils.transcription(originFile, AudioResponseFormatEnum.TEXT);
//        return fileText;
//    }
//
//    @Override
//    @SneakyThrows
//    public String voice2English(MultipartFile file) {
//        Resource resource = file.getResource();
//        File originFile = resource.getFile();
//        return OpenAiUtils.translation(originFile, AudioResponseFormatEnum.TEXT);
//
//    }
//
//    @Override
//    public void talkMange(String message) {
//        OpenAiUtils.createStreamChatCompletion(message);
//    }
//
//    @Override
//    public String downloadImage(String desc) {
//
//        return desc;
//    }
//
//    @Override
//    public void talkWebSocket(UserMessage userMessage, WebSocketController webSocketController, Session session) {
//
//    }
//}
